package com.nzy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nzy.common.RedisUtil;
import com.nzy.common.CacheKey;
import com.nzy.controller.request.ListGoodsRequest;
import com.nzy.controller.response.ListGoodsResponse;
import com.nzy.dao.mapper.GoodsMapper;
import com.nzy.entity.Goods;
import com.nzy.service.GoodsService;
import com.nzy.service.StockFeignService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private StockFeignService stockFeignService;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    @Transactional
    public int insert(Goods goods, Integer number) {
        Date date = new Date();
        goods.setCreateTime(date);
        goods.setUpdateTime(date);
        goods.setState(0);
        int result = goodsMapper.insert(goods);
        String key = CacheKey.getGoodsBySkuId(goods.getSkuId());
        redisUtil.set(key, JSONObject.toJSONString(goods));
        stockFeignService.createStock(goods.getSkuId(), number, "goods");
        return  result;
    }

    @Override
    public List<ListGoodsResponse> queryList(ListGoodsRequest request) {
        Page page = PageHelper.startPage(request.getPageNum(), request.getPageSize());
        Goods goods = new Goods();
        List<Goods> goodsList =  goodsMapper.selectBySelect(goods);
        List<ListGoodsResponse> result = new ArrayList<>();
        for(Goods g: goodsList){
            ListGoodsResponse response = new ListGoodsResponse();
            BeanUtils.copyProperties(g, response);
            response.setStock(getStock(response.getSkuId()));
            result.add(response);
        }
        return result;
    }

    @Override
    public Goods queryById(Integer id) {
        return goodsMapper.selectByPrimaryKey(id);
    }

    @Override
    public Goods queryBySkuId(String skuId) {
        String key = CacheKey.getGoodsBySkuId(skuId);
        Goods goods = redisUtil.getBean(key, Goods.class);
        if(goods == null){
            goods = goodsMapper.selectBySkuId(skuId);
            redisUtil.set(key, goods);
        }
        return goods;
    }


    private Integer getStock(String skuId){
        Integer result = 0;
        try{
            String response = stockFeignService.getStock(skuId);
            JSONObject jsonObject = JSONObject.parseObject(response);
            if (jsonObject.getIntValue("code") == 200){
                result = jsonObject.getIntValue("data");
            }
        }catch (Exception e){

        }
        return  result;
    }
}
